

import React, { useState, useEffect } from 'react';
import { View, Text, ScrollView, TouchableOpacity } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter, useLocalSearchParams } from 'expo-router';
import { FontAwesome5, FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import Animated, { useSharedValue, useAnimatedStyle, withTiming, withDelay, withSequence, withRepeat } from 'react-native-reanimated';
import styles from './styles';

interface ResultInfo {
  icon: string;
  iconStyle: string;
  title: string;
  subtitle: string;
  actionResult: string;
  actionIcon: string;
  actionIconColor: string;
  actionBgColor: string;
}

const ApprovalProcessScreen = () => {
  const router = useRouter();
  const params = useLocalSearchParams();
  
  const [resultInfo, setResultInfo] = useState<ResultInfo>({
    icon: 'check',
    iconStyle: 'success',
    title: '审批已通过',
    subtitle: '您的审批操作已成功提交',
    actionResult: '审批通过',
    actionIcon: 'check',
    actionIconColor: '#10B981',
    actionBgColor: '#D1FAE5'
  });

  const [processInstanceId] = useState<string>((params.processInstanceId as string) || 'AP-20240115-001');
  const [currentTime, setCurrentTime] = useState<string>('');

  // 动画值
  const containerOpacity = useSharedValue(0);
  const containerTranslateY = useSharedValue(20);
  const iconScale = useSharedValue(0.8);
  const iconOpacity = useSharedValue(0);

  useEffect(() => {
    // 设置当前时间
    const now = new Date();
    const timeString = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
    setCurrentTime(timeString);

    // 根据操作类型设置结果信息
    const action = (params.action as string) || 'approve';
    setResultInfoByAction(action);

    // 启动动画
    startAnimations();
  }, [params.action]);

  const setResultInfoByAction = (action: string) => {
    switch (action) {
      case 'approve':
        setResultInfo({
          icon: 'check',
          iconStyle: 'success',
          title: '审批已通过',
          subtitle: '您的审批操作已成功提交',
          actionResult: '审批通过',
          actionIcon: 'check',
          actionIconColor: '#10B981',
          actionBgColor: '#D1FAE5'
        });
        break;
      case 'reject':
        setResultInfo({
          icon: 'times',
          iconStyle: 'error',
          title: '审批已驳回',
          subtitle: '审批已退回至发起人',
          actionResult: '审批驳回',
          actionIcon: 'times',
          actionIconColor: '#EF4444',
          actionBgColor: '#FEE2E2'
        });
        break;
      case 'transfer':
        setResultInfo({
          icon: 'share-alt',
          iconStyle: 'info',
          title: '转办成功',
          subtitle: '审批任务已成功转交给其他用户',
          actionResult: '转办成功',
          actionIcon: 'share-alt',
          actionIconColor: '#3B82F6',
          actionBgColor: '#DBEAFE'
        });
        break;
      case 'return':
        setResultInfo({
          icon: 'undo',
          iconStyle: 'warning',
          title: '已退回上一步',
          subtitle: '审批已退回至流程上一节点',
          actionResult: '退回上一步',
          actionIcon: 'undo',
          actionIconColor: '#F59E0B',
          actionBgColor: '#FEF3C7'
        });
        break;
      default:
        setResultInfo({
          icon: 'check',
          iconStyle: 'success',
          title: '操作成功',
          subtitle: '您的操作已成功完成',
          actionResult: '操作成功',
          actionIcon: 'check',
          actionIconColor: '#10B981',
          actionBgColor: '#D1FAE5'
        });
    }
  };

  const startAnimations = () => {
    // 容器动画
    containerOpacity.value = withTiming(1, { duration: 600 });
    containerTranslateY.value = withTiming(0, { duration: 600 });

    // 图标动画
    iconOpacity.value = withDelay(100, withTiming(1, { duration: 500 }));
    iconScale.value = withDelay(100, withSequence(
      withTiming(1.1, { duration: 400 }),
      withTiming(1, { duration: 300 })
    ));
  };

  const containerAnimatedStyle = useAnimatedStyle(() => {
    return {
      opacity: containerOpacity.value,
      transform: [{ translateY: containerTranslateY.value }],
    };
  });

  const iconAnimatedStyle = useAnimatedStyle(() => {
    return {
      opacity: iconOpacity.value,
      transform: [{ scale: iconScale.value }],
    };
  });

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    }
  };

  const handleBackToListPress = () => {
    router.push('/p-pending_approval');
  };

  const handleViewDetailPress = () => {
    router.push(`/p-approval_detail?processInstanceId=${processInstanceId}`);
  };

  const getResultIconGradient = () => {
    switch (resultInfo.iconStyle) {
      case 'success':
        return ['#10B981', '#059669'];
      case 'error':
        return ['#EF4444', '#DC2626'];
      case 'warning':
        return ['#F59E0B', '#D97706'];
      case 'info':
        return ['#3B82F6', '#2563EB'];
      default:
        return ['#10B981', '#059669'];
    }
  };

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <TouchableOpacity 
          style={styles.backButton} 
          onPress={handleBackPress}
          activeOpacity={0.7}
        >
          <FontAwesome6 name="arrow-left" size={18} color="#1F2937" />
        </TouchableOpacity>
        <Text style={styles.headerTitle}>审批结果</Text>
        <View style={styles.headerPlaceholder} />
      </View>

      {/* 主要内容区域 */}
      <ScrollView 
        style={styles.scrollView}
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        <Animated.View style={[styles.resultContainer, containerAnimatedStyle]}>
          {/* 结果图标 */}
          <View style={styles.resultIconContainer}>
            <Animated.View style={iconAnimatedStyle}>
              <LinearGradient
                colors={getResultIconGradient()}
                style={styles.resultIcon}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <FontAwesome6 name={resultInfo.icon} size={32} color="#FFFFFF" />
              </LinearGradient>
            </Animated.View>
          </View>

          {/* 结果标题 */}
          <View style={styles.resultTitleContainer}>
            <Text style={styles.resultTitle}>{resultInfo.title}</Text>
            <Text style={styles.resultSubtitle}>{resultInfo.subtitle}</Text>
          </View>

          {/* 结果详情 */}
          <View style={styles.resultDetails}>
            <View style={styles.detailItem}>
              <LinearGradient
                colors={['#969FFF', '#5147FF']}
                style={styles.detailIcon}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <FontAwesome5 name="file-alt" size={16} color="#FFFFFF" />
              </LinearGradient>
              <View style={styles.detailContent}>
                <Text style={styles.detailTitle}>员工请假申请</Text>
                <Text style={styles.detailSubtitle}>审批单号：{processInstanceId}</Text>
              </View>
            </View>
            
            <View style={styles.detailItem}>
              <View style={[styles.detailIcon, { backgroundColor: resultInfo.actionBgColor }]}>
                <FontAwesome6 name={resultInfo.actionIcon} size={16} color={resultInfo.actionIconColor} />
              </View>
              <View style={styles.detailContent}>
                <Text style={styles.detailTitle}>操作类型</Text>
                <Text style={styles.detailSubtitle}>{resultInfo.actionResult}</Text>
              </View>
            </View>
            
            <View style={styles.detailItem}>
              <View style={[styles.detailIcon, { backgroundColor: '#DBEAFE' }]}>
                <FontAwesome6 name="clock" size={16} color="#3B82F6" />
              </View>
              <View style={styles.detailContent}>
                <Text style={styles.detailTitle}>处理时间</Text>
                <Text style={styles.detailSubtitle}>{currentTime}</Text>
              </View>
            </View>
          </View>

          {/* 操作建议 */}
          <View style={styles.suggestions}>
            <View style={styles.suggestionHeader}>
              <FontAwesome6 name="lightbulb" size={16} color="#F59E0B" />
              <Text style={styles.suggestionTitle}>下一步建议</Text>
            </View>
            <View style={styles.suggestionList}>
              <View style={styles.suggestionItem}>
                <View style={styles.suggestionBullet} />
                <Text style={styles.suggestionText}>审批已流转至下一节点，您可以随时查看审批进度</Text>
              </View>
              <View style={styles.suggestionItem}>
                <View style={styles.suggestionBullet} />
                <Text style={styles.suggestionText}>如需了解更多详情，可查看完整的审批记录</Text>
              </View>
            </View>
          </View>

          {/* 操作按钮 */}
          <View style={styles.actionButtons}>
            <TouchableOpacity 
              style={styles.primaryButton} 
              onPress={handleBackToListPress}
              activeOpacity={0.8}
            >
              <LinearGradient
                colors={['#969FFF', '#5147FF']}
                style={styles.primaryButtonGradient}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
              >
                <FontAwesome6 name="list" size={16} color="#FFFFFF" />
                <Text style={styles.primaryButtonText}>返回待办列表</Text>
              </LinearGradient>
            </TouchableOpacity>
            
            <TouchableOpacity 
              style={styles.secondaryButton} 
              onPress={handleViewDetailPress}
              activeOpacity={0.8}
            >
              <FontAwesome6 name="eye" size={16} color="#969FFF" />
              <Text style={styles.secondaryButtonText}>查看审批详情</Text>
            </TouchableOpacity>
          </View>
        </Animated.View>
      </ScrollView>
    </SafeAreaView>
  );
};

export default ApprovalProcessScreen;

